import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import * as path from "node:path";
import commonjs from "@rollup/plugin-commonjs";
import { visualizer } from "rollup-plugin-visualizer";
import { babel } from "@rollup/plugin-babel";

export default defineConfig({
  plugins: [
    uni(),
    {
      name: "fix-rollup-conflict",
      configResolved(config) {
        if (config.build?.rollupOptions?.output) {
          const output = config.build.rollupOptions.output;
          delete output.manualChunks;
          output.preserveModules = true;
          output.preserveModulesRoot = "src";
        }
      },
    },
    // 关键：添加Babel插件处理ES6+语法
    babel({
      babelrc: false,
      presets: [
        [
          "@babel/preset-env",
          {
            targets: {
              browsers: ["android >= 7"], // 目标安卓7+系统
            },
            useBuiltIns: "entry",
            corejs: "3.32.0",
          },
        ],
      ],
      include: ["**/*.js", "**/*.ts", "**/*.vue"],
      exclude: "node_modules/**",
      babelHelpers: "bundled",
    }),
    // 将ES模块转换为CommonJS
    commonjs({
      include: "**/*.js",
      transformMixedEsModules: true,
      ignoreDynamicRequires: false,
    }),
  ],
  build: {
    outDir: "libs",
    minify: "terser",
    lib: {
      entry: path.resolve(__dirname, "./src/components/index.ts"),
      name: "libs",
      fileName: (format) => `isafety-ui.${format}.js`,
      formats: ["cjs"], // 输出CommonJS格式
    },
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    rollupOptions: {
      output: {
        format: "cjs",
        chunkFileNames: "chunks/[name]-[hash].js",
        entryFileNames: "[name]-[hash].js",
        exports: "auto",
        preserveModules: true,
        preserveModulesRoot: "src",
      },
      external: [
        "vue",
        "element-plus",
        "vue-element-plus-x",
        /^@?[a-z0-9-]+(\/.*)?$/,
      ],
      plugins: [
        visualizer({
          open: false,
          filename: "dist/build-analysis.html",
        }),
      ],
    },
  },
  resolve: {
    alias: {
      "vue-element-plus-x": path.resolve(__dirname, "node_modules/vue-element-plus-x/dist"),
      "@": path.resolve(__dirname, "src"),
      // 核心模块polyfill（安卓环境需要）
      "stream": "rollup-plugin-node-polyfills/polyfills/stream",
      "buffer": "rollup-plugin-node-polyfills/polyfills/buffer",
      "process": "rollup-plugin-node-polyfills/polyfills/process",
    },
    extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json"],
  },
  esbuild: {
    format: "cjs",
    jsxFactory: "h",
    jsxFragment: "Fragment",
    loader: { ".js": "jsx" },
    // 简化目标配置，由Babel处理转换
    target: ["es2019"],
    define: {
      "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "production"),
      global: "globalThis",
    },
  },
});